<?php

namespace app\controller\system;

use app\controller\BaseController;
use app\model\system\SysMenu;
use app\model\system\SysUser;
use support\Request;
use support\Response;

class MenuController extends BaseController
{

    public function create(Request $request): Response
    {
        $data = $request->post();
        $user = SysUser::create($data);
        if (!$user) {
            return $this->error('创建失败');
        } else {
            return $this->success([]);
        }
    }

    public function form(int $id): Response
    {
        $menu = SysMenu::find($id);
        if (!$menu) {
            return $this->error('数据不存在');
        }

        return $this->success($menu->toArray());
    }

    public function update(Request $request, int $id): Response
    {
        $data = $request->post();
        $menu = SysMenu::find($id);
        if (!$menu) {
            return $this->error('数据不存在');
        }
        $menu->update($data);
        return $this->success($menu->toArray());
    }

    public function delete(Request $request, int $id): Response
    {
        $menu = SysMenu::find($id);
        if (!$menu) {
            return $this->error('数据不存在');
        }
        $menu->deleteNode();
        return $this->success($menu->toArray());
    }

    public function visible(Request $request, int $id): Response
    {
        $visible = $request->post("visible", 1);
        $menu = SysMenu::find($id);
        if (!$menu) {
            return $this->error('数据不存在');
        }
        $menu->visible = $visible;
        $menu->save();
        return $this->success($menu->toArray());
    }

    public function get(Request $request): Response
    {
        $keywords = $request->get("keywords");
        $status = $request->get("status");
        $menus = SysMenu::getTreeMenus(0, $status, $keywords);
        return $this->success($menus);
    }

    public function routes(Request $request): Response
    {
        $jwtUser = $request->currUser;
        $user = SysUser::find($jwtUser->userId);
        if (!$user) {
            return $this->error('数据不存在');
        }
        return $this->success($user->getTreeMenus());
    }

    public function options(): Response
    {
        $options = SysMenu::getMenusOptions();
        return $this->success($options);
    }
}
